package imgsquash

import (
	"os"
	"path/filepath"
	"time"

	"gitee.com/yinxulai/PrivateToolServer/services/fileinn"
	"gitee.com/yinxulai/PrivateToolServer/services/workqueue"
	"gopkg.in/gographics/imagick.v2/imagick"
)

// WorkType 注册的处理类型
const WorkType = "IMGSQUASH"

// 实现一个处理器
type worker struct {
}

func (w worker) Async() bool {
	return true
}
func (w worker) Type() string {
	return WorkType
}
func (w worker) Handle(work workqueue.Work, callback func(*workqueue.Work)) {
	var err error
	matter := work.Matter.(Matter)
	matter.Ouput, err = SquashFileInn(matter.Input, matter.Quality)
	if err != nil {
		work.State = workqueue.Failure
		callback(&work)
	}
	work.State = workqueue.Success
	work.Matter = matter
	callback(&work)
}

// Matter 定义自己能处理的课题
type Matter struct {
	Input   fileinn.File
	Ouput   fileinn.File
	Quality uint
}

func init() {
	wker := worker{}
	workqueue.RegisterWorker(wker)
}

// Squash 压缩
func Squash(src string, quality uint) (out string, err error) {
	imagick.Initialize()
	defer imagick.Terminate()
	mw := imagick.NewMagickWand()
	err = mw.ReadImage(src)
	if err != nil {
		return "", err
	}
	err = mw.SetImageCompressionQuality(quality)
	if err != nil {
		return "", err
	}

	err = mw.WriteImage(out)
	if err != nil {
		return "", err
	}
	return
}

// SquashFileInn 压缩
func SquashFileInn(src fileinn.File, quality uint) (out fileinn.File, err error) {
	imagick.Initialize()
	defer imagick.Terminate()
	mw := imagick.NewMagickWand()
	err = mw.ReadImage(src.Path)
	if err != nil {
		return fileinn.File{}, err
	}
	err = mw.SetImageCompressionQuality(quality)
	if err != nil {
		return fileinn.File{}, err
	}
	tempPath, err := fileinn.GetTempDir("SquashFileInn", time.Minute*1)
	filePath := filepath.Join(tempPath, src.Name)
	err = mw.WriteImage(filePath)

	output, err := fileinn.SaveFilePath(filePath, time.Minute*10)
	if err != nil {
		return fileinn.File{}, err
	}
	return *output, nil
}

// SquashFile 压缩
func SquashFile(file *os.File, quality uint) (out string, err error) {
	imagick.Initialize()
	defer imagick.Terminate()
	mw := imagick.NewMagickWand()
	err = mw.ReadImageFile(file)
	if err != nil {
		return "", err
	}
	err = mw.SetImageCompressionQuality(quality)
	if err != nil {
		return "", err
	}

	err = mw.WriteImage(out)
	if err != nil {
		return "", err
	}
	return
}

// SquashBlob 压缩
func SquashBlob(blob []byte, quality uint) (out string, err error) {
	imagick.Initialize()
	defer imagick.Terminate()
	mw := imagick.NewMagickWand()
	err = mw.ReadImageBlob(blob)
	if err != nil {
		return "", err
	}
	err = mw.SetImageCompressionQuality(quality)
	if err != nil {
		return "", err
	}
	err = mw.WriteImage(out)
	if err != nil {
		return "", err
	}
	return
}
